import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Scanner;

public class OhMyNet {
    public static void main(String[] args) throws JSchException, IOException {
        Conf conf = load();
        Host host = conf.getHost();
        System.out.println("Use server:\n  " + host);
        JSch jSch = new JSch();
        jSch.addIdentity(System.getProperty("user.home") + "/.ssh/id_rsa", "");
        Session session = jSch.getSession(host.getUser(), host.getHost(), host.getPort());
        session.setConfig("PreferredAuthentications", "publickey");
        session.setConfig("StrictHostKeyChecking", "no");
        session.setConfig("UseDNS", "no");
        session.connect();
        System.out.println("Connected:\n  " + session.getServerVersion());
        for (Proxy proxy : conf.getProxy()) {
            System.out.println("Create proxy:\n  " + proxy);
            session.setPortForwardingL(proxy.getLocal().getHost(), proxy.getLocal().getPort(), proxy.getTarget().getHost(), proxy.getTarget().getPort());
        }
        System.in.read();
    }

    private static final String FILE = "oh-my-net.txt";

    public static Conf load() {
        File file;
        URL url = OhMyNet.class.getResource("");
        if (url != null) {
            file = new File(url.getPath(), FILE);
        } else {
            file = new File(FILE);
        }
        System.out.println("Read config:\n  " + file.getAbsolutePath());
        if (!file.exists()) {
            if (!file.exists()) {
                throw new RuntimeException("oh-my-net.txt not found.");
            }
        }
        Conf conf = new Conf();
        try (FileInputStream fis = new FileInputStream(file)) {
            Scanner scanner = new Scanner(fis);
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine().trim();
                if (!line.startsWith("//")) {
                    if (line.contains("@") && line.contains(":") && conf.getProxy().isEmpty()) {
                        Host host = new Host(line);
                        conf.setHost(host);
                    } else if (line.contains(" > ")) {
                        String[] arr = line.split(" > ");
                        Host local = new Host(arr[0]);
                        Host target = new Host(arr[1]);
                        conf.add(new Proxy(local, target));
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return conf;
    }
}
